package mao.leetcode.others.leetcode95;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<TreeNode> generateTrees(int n) {
        if (n<1) return new ArrayList<TreeNode>();  //一般要求返回里面为空，而不是null,对于调用代码来说，容易空指针异常
        return generateTrees(1,n);
    }

    public List<TreeNode> generateTrees(int start, int end){
        List<TreeNode> list = new ArrayList<>();
        if (start > end ) {
            list.add(null);
            return list;
        }

        for (int i = start; i <= end; i++) {
             List<TreeNode> lefts = generateTrees(start, i - 1);
             List<TreeNode> rights = generateTrees(i + 1, end);
            for (TreeNode left : lefts) {
                for (TreeNode right : rights) {
                    TreeNode root = new TreeNode(i);
                    root.left = left;
                    root.right = right;
                    list.add(root);
                }
            }
        }
        return list;
    }

    public class TreeNode {
         int val;
          TreeNode left;
         TreeNode right;
        TreeNode(int x) { val = x; }
  }
}
